package dper.study.codes.concurrent.model;

import org.apache.log4j.Logger;

import java.util.LinkedList;
import java.util.concurrent.Semaphore;

/**
 * Created by leichen on 2017/3/21.
 */
public class ProConBufferSemaphore implements ProConBuffer {
    Logger logger = Logger.getLogger(ProConBufferSemaphore.class) ;

    private int bufferLen = 10 ;

    private LinkedList<Integer> buffer = new LinkedList<Integer>() ;

    private Semaphore isEmpty = new Semaphore(0,true) ;

    private Semaphore isFull = new Semaphore(10,true) ;

    private Semaphore mutex = new Semaphore(1,true) ;

    public void set(int i) {
        try {
            isFull.acquire();
            mutex.acquire();
            buffer.add(i) ;
            logger.info(Thread.currentThread()+"\tproducer add "+i+" in buffer\tNow size " + buffer.size());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            mutex.release();
            isEmpty.release();
        }
    }

    public int get() throws InterruptedException {
        try {
            isEmpty.acquire();
            mutex.acquire();
            int head = buffer.poll();
            logger.info(Thread.currentThread()+"\tconsumer consume "+ head+" from buffer\tNow size " + buffer.size() );
            return head ;
        }finally {
            mutex.release();
            isFull.release();
        }

    }
}
